package com.situ.orderingsystem.global;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebListener
public class LoadListener  implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContextListener.super.contextInitialized(sce);
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
        Properties pro = new Properties();
        try {
            pro.load(is);
            String driver = pro.getProperty("jdbc.driver");
            String url = pro.getProperty("jdbc.url");
            String user = pro.getProperty("jdbc.user");
            String pwd = pro.getProperty("jdbc.pwd");
            Global.createDataSource(driver,url,user,pwd);
//            System.out.println("连接数据库成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
//            System.out.println("连接数据库关闭");
            try {
                is.close();
            } catch (IOException e) {
                   throw new RuntimeException(e);
            }
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContextListener.super.contextDestroyed(sce);
    }
}
